package com.ccc.boot.system.config;

import cn.hutool.json.JSONUtil;
import com.ccc.boot.redis.constant.RedisConstant;
import com.ccc.boot.redis.util.RedisUtils;
import com.ccc.boot.system.service.SysDictInfoService;
import com.ccc.boot.system.service.SysDictService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

/**
 * 配置启动执行方法
 *
 * @author superC
 * @version 0.1.0
 * @date 2022/4/1
 */

@Configuration
public class WebStartConfig {

    private static final Logger logger = LoggerFactory.getLogger(WebStartConfig.class);

    @Resource
    private SysDictService sysDictService;

    @Resource
    private SysDictInfoService sysDictInfoService;

    @Autowired
    private RedisUtils redisUtils;

    @PostConstruct
    public void initData() {
        // 向缓存存储数据-数据字典
        storageDictToRedis();
    }

    /**
     * @return void
     * @author superC
     * @description 向缓存存储数据-数据字典
     * @date 2020/12/25 10:45
     */
    private void storageDictToRedis() {
        logger.info("REDIS -> 数据字典 START");
        String key = RedisConstant.SYS_DICT_DATAS;

        // 先清空
        if (redisUtils.hasKey(key)) {
            redisUtils.del(key);
        }

        Set<String> ids = sysDictService.getAllIds();
        ids.forEach(id -> {

            // 再缓存
            Map<String, Object> objectMap = sysDictInfoService.selectMap(id);
            if (!objectMap.isEmpty()) {
                redisUtils.hSet(key, id, JSONUtil.toJsonStr(objectMap));
            }

        });
        logger.info("REDIS -> 数据字典 END");
    }

}
